package com.xiebishe.mylibrary.common.dialog.loading;

import androidx.annotation.LayoutRes;
import androidx.annotation.NonNull;
import androidx.fragment.app.FragmentActivity;
import androidx.lifecycle.DefaultLifecycleObserver;
import androidx.lifecycle.LifecycleOwner;

import com.xiebishe.mylibrary.base.MyActivityManager;


/**
 * @class ProgressDialogHelper
 * @describe 页面中间的loading框
 */
public class LoadingHelper {
    private static LoadingDialog loadingDialog;

    public static void show() {
        FragmentActivity activity = (FragmentActivity) MyActivityManager.getInstance().getCurrentActivity();
        if (loadingDialog != null && loadingDialog.isShowing() && loadingDialog.getOwnerActivity() == activity) {
            return;
        }

        if (activity != null) {
            loadingDialog = new LoadingDialog(activity);
            loadingDialog.setOwnerActivity(activity);
            loadingDialog.show();

            activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onStop(@NonNull LifecycleOwner owner) {
                    if (loadingDialog == null || loadingDialog.getOwnerActivity() != activity) {
                        return;
                    }
                    dismissLoading();
                }
            });
        }

    }

    public static void show(@LayoutRes int layoutResID) {
        FragmentActivity activity = (FragmentActivity) MyActivityManager.getInstance().getCurrentActivity();
        if (loadingDialog != null && loadingDialog.isShowing() && loadingDialog.getOwnerActivity() == activity) {
            return;
        }

        if (activity != null) {
            loadingDialog = new LoadingDialog(activity, layoutResID);
            loadingDialog.setOwnerActivity(activity);
            loadingDialog.show();

            activity.getLifecycle().addObserver(new DefaultLifecycleObserver() {
                @Override
                public void onStop(@NonNull LifecycleOwner owner) {
                    if (loadingDialog == null || loadingDialog.getOwnerActivity() != activity) {
                        return;
                    }
                    dismissLoading();
                }
            });
        }

    }

    private static void dismissLoading() {
        if (loadingDialog == null) {
            return;
        }
        try {
            if (loadingDialog.isShowing()) {
                loadingDialog.dismiss();
            }
        } catch (Exception e) {
        } finally {
            loadingDialog = null;
        }
    }

    public static void cancel() {
        dismissLoading();
    }

}
